/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package alcatelparser.modules;

import alcatelparser.errors.ParseFailedException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 *
 * @author geniuz
 */
public class PreparseAnalyzer {

    public PreparseAnalyzer(TagFactory tagfactory)
    {
        //LOG = Logger.getLogger(com/alcatel/algo/PreparseAnalyzer);
        _tFactory = tagfactory;
    }
    public byte[] getUnsignedbytes(byte[] bytes){
    int length = bytes.length;
    byte[] newbytes = new byte[length];
    for (int step = 0; step < length; step++){
        int byteValue = new Integer(bytes[step]).intValue( );
        if (byteValue < 0 ){
            byteValue = bytes[step] & 0x80;
            byteValue += bytes[step] & 0x7F;
        }
        newbytes[step] = (byte)byteValue;
    }
    return newbytes;
}
    
    
        public static byte[] getBytesFromFile(File file, int len) throws IOException {
        InputStream is = new FileInputStream(file);
        // Get the size of the file
        long length = len;
    
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }
    
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];
    
        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        }
    
        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
    
        // Close the input stream and return bytes
        is.close();
        return bytes;
    }
    public final File preparseAnalyze(File file) throws FileNotFoundException, IOException, ParseFailedException
    {
        byte abyte0[];
        //Encoding d=new Encoding(file.getAbsolutePath());
        //InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream (file), "ASCII");
        BufferedReader bufferedreader = new BufferedReader(new FileReader(file));//
        String s = bufferedreader.readLine();
        abyte0 = getBytesFromFile(file,s.length());
        char[] ch = s.toCharArray();
        int y = (int)ch[1];
        byte bbb = (byte)ch[1];
        if(!Env.getEnv().isAutoSourceFileSettingsDefine())
        {}//break MISSING_BLOCK_LABEL_65;
        if(isBinary(abyte0))
        {
            applyBinaryStartParseIndex(abyte0);
            return checkBinaryFormat(file);
        }
        try
        {
            return prepareTextFile(file, abyte0);
        }
        catch(FileNotFoundException filenotfoundexception)
        {
            //System.out.print(filenotfoundexception.getMessage()+"\n");
            throw new ParseFailedException(I.I(7856));
        }
        catch(IOException ioexception)
        {
            //System.out.print(ioexception.getMessage()+"\n");
            //LOG.error(ioexception);
        }
        //break MISSING_BLOCK_LABEL_126;
        if(Env.getEnv().isBinary())
        {
            applyBinaryStartParseIndex(abyte0);
            return checkBinaryFormat(file);
        }
        return prepareTextFile(file, abyte0);
    }

    private void applyBinaryStartParseIndex(byte abyte0[])
    {
        if(Env.getEnv().isWorkConditionsAuto())
        {
            byte byte0 = abyte0[0];
            if(byte0 == -93 || byte0 == 163)
                _tFactory.setStartParseTagIndex(TagFactory.TEXT_FILE_RECORD_PARSE_INDEX);
        } else
        {
            _tFactory.setStartParseTagIndex(Env.getEnv().isRepairMode() ? TagFactory.TEXT_FILE_RECORD_PARSE_INDEX : 0);
        }
    }

    private File checkBinaryFormat(File file)
    {
        if(Env.getEnv().isRepairMode())
            return file;
        if(Env.getEnv().isWorkConditionsAuto())
            return file;
        if(Env.getEnv().isStandardMode())
            return file;
        else
            return file;
    }

    private File prepareTextFile(File file, byte abyte0[]) throws FileNotFoundException, ParseFailedException, IOException
    {
        if(isBinary(abyte0))
        {
            throw new ParseFailedException(I.I(7721));
        } else
        {
            _tFactory.setStartParseTagIndex(TagFactory.TEXT_FILE_RECORD_PARSE_INDEX);
            File file1 = new File((new StringBuilder()).append(I.I(7768)).toString());
            //System.out.print(file1.getAbsolutePath()+"\nSuccess\n");
            (new Txt2BinConverter()).convertToBin(file, file1);
            
            return file1;
        }
    }

    private boolean isBinary(byte abyte0[])
    {
        if(abyte0 == null || abyte0.length == 0)
            return false;
        if(abyte0.length < 2)
            return false;
        byte byte0 = abyte0[0];
        byte byte1 = abyte0[1];
        return byte0 == 163 || byte0 == -93 || byte0 == 48 && (byte1 == 128 || byte1 == -128);
    }

    //private Logger LOG;
    private TagFactory _tFactory;
    public static final String CONVERTED_FILE_NAME = "s12parser_converted_text_file.txt";
}
